import * as vscode from "vscode";
import { statSync } from "node:fs";
import { sep, parse } from "node:path";
import { handleCompName } from "../util.js";
import { getConfiguration } from "../vsUtil.js";


export default (context: vscode.ExtensionContext) => {
  const disposable = vscode.commands.registerCommand("an-tools.copyCompImport", (clickFileUrl: vscode.Uri, filePaths: vscode.Uri[]) => {

    let importStr = "";
    let flog = false; // 复制成功的标识
    const ailasList: ObjectType | void = getConfiguration("an-tools.path.ailas");

    if (!ailasList || !Object.keys(ailasList).length) {
      vscode.window.showErrorMessage("没有获取别名相关的配置, 请检查 path.ailas 配置项");
      return;
    }

    for (const item of filePaths) {
      const url = item.fsPath;

      if (statSync(url).isDirectory()) {
        vscode.window.showErrorMessage("复制目录是无效的哦!");
        continue;
      }

      const fileName = parse(url).name;
      if (!fileName && !fileName.trim()) {
        vscode.window.showErrorMessage("文件名无效: ", fileName);
        continue;
      }

      // 别名匹配
      for (const [alias, path] of Object.entries(ailasList)) {
        const compName = handleCompName(fileName);
        const pathRE = new RegExp(sep.repeat(2) + path + sep.repeat(2));
        const result: RegExpExecArray | null = pathRE.exec(url);

        if (result) {
          const importPath = url.slice(result.index).replace(pathRE, alias + sep);
          importStr += `import ${compName} from "${importPath}";\r\n`.replaceAll(sep, "/");
          flog = true;
          continue;
        }
      }

      if (!flog) {
        // 单个别名未匹配
        vscode.window.showErrorMessage(`没有匹配到 ${url} 这个路径对应的别名`);
      } else {
        flog = true;
      }
    }
    // 复制路径
    vscode.env.clipboard.writeText(importStr);
    if (importStr.trim()) {
      vscode.window.showInformationMessage("路径复制成功");
    }
  });
  context.subscriptions.push(disposable);
}